import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SiteConfig } from './config.entity';

@Injectable()
export class ConfigService {
  constructor(
    @InjectRepository(SiteConfig)
    private configRepository: Repository<SiteConfig>,
  ) {}

  async findAll(): Promise<SiteConfig[]> {
    return await this.configRepository.find();
  }

  async findOne(id: number): Promise<SiteConfig | null> {
    return await this.configRepository.findOne({ where: { id } });
  }

  async findByKey(key: string): Promise<SiteConfig | null> {
    return await this.configRepository.findOne({ where: { key } });
  }

  async create(configData: Partial<SiteConfig>): Promise<SiteConfig> {
    const config = this.configRepository.create(configData);
    return await this.configRepository.save(config);
  }

  async update(id: number, configData: Partial<SiteConfig>): Promise<SiteConfig | null> {
    await this.configRepository.update(id, configData);
    return await this.configRepository.findOne({ where: { id } });
  }

  async remove(id: number): Promise<void> {
    await this.configRepository.delete(id);
  }

  /**
   * 批量更新配置
   * @param configs 配置键值对数组
   */
  async batchUpdate(configs: { key: string; value: string }[]): Promise<void> {
    for (const config of configs) {
      const existingConfig = await this.findByKey(config.key);
      if (existingConfig) {
        await this.update(existingConfig.id, { value: config.value });
      } else {
        await this.create({ key: config.key, value: config.value });
      }
    }
  }

  /**
   * 获取配置值
   * @param key 配置键
   * @param defaultValue 默认值
   */
  async getConfigValue(key: string, defaultValue: string = ''): Promise<string> {
    const config = await this.findByKey(key);
    return config ? config.value : defaultValue;
  }
}